package com.example.demo.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;



public class HashUtil {
    public static String hashPassword(String password) {
        //获取SHA-256算法生成哈希值
        try{
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            //计算哈希值
            byte[] hashBytes = digest.digest(password.getBytes(StandardCharsets.UTF_8));
            //将字符串转换为十六进制字符串
            return bytesToHex(hashBytes);
        }catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256算法不可用",e);
        }
    }
    //验证密码是否匹配
    public static boolean verifyPassword(String password, String hashedPassword) {
        //对输入的密码进行哈希计算
        String inputHash = hashPassword(password);
        //比较哈希值
        return inputHash.equals(hashedPassword);
    }
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for(byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if(hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
    return hexString.toString();
    }
}
